/* Copyright 2014 Nate Eisner, Noah Bahr
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package edu.uwp.kcwm;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class ExhibitArtifacts extends Activity {
	private ImageView imgV;

	Intent intent;
	String exhibitNum;

	private ProgressDialog pDialog;

	// URL for webserver
	private static final String SITEURL = "http://gracefullyengineered.com/kcwm/";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exhibitartifacts);
		pDialog = new ProgressDialog(this);

		// get exhibit number
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			exhibitNum = extras.getString("exhibitNum");
		}
		getActionBar().setTitle("Exhibit " + exhibitNum + " - Artifacts");

		new LoadPics().execute(SITEURL + exhibitNum + "/artifacts.html");
	}

	/**
	 * Used when a artifact image is clicked to goto that artifact's info
	 * 
	 * @param view
	 *            ImageView of the clicked artifact
	 * @param num
	 *            the number of artifact
	 */
	public void showArtifact(View view, int num) {
		Intent intent = new Intent(ExhibitArtifacts.this, Artifact.class);
		intent.putExtra("exhibitNum", exhibitNum);
		intent.putExtra("artifactNum", Integer.toString(num));
		ExhibitArtifacts.this.startActivity(intent);
	}

	/**
	 * AsyncTask to get artifact count from artifacts.html and loads pictures
	 * from the /artifacts/ directory starting at 1.jpg...
	 */
	class LoadPics extends AsyncTask<String, Void, ArrayList<Bitmap>> {
		protected int artCount;

		protected void onPreExecute() {
			pDialog.setMessage("Loading Artifacts...");
			pDialog.show();
		}

		/**
		 * Gets artifact count from artifacts.html file and loads
		 * bitmaps of the artifacts into arraylist
		 */
		@Override
		protected ArrayList<Bitmap> doInBackground(String... urlStr) {
			// do stuff on non-UI thread
			String htmlCode = "";
			Bitmap bitmap = null;
			ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
			try {
				URL url = new URL(urlStr[0]);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						url.openStream()));

				String inputLine;

				while ((inputLine = in.readLine()) != null) {
					htmlCode = inputLine;
				}

				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			artCount = Integer.parseInt(htmlCode);
			for (int i = 1; i <= artCount; i++) {
				String url = SITEURL + exhibitNum + "/artifacts/" + i + ".jpg";

				try {
					bitmap = BitmapFactory.decodeStream((InputStream) new URL(
							url).getContent());
					if (bitmap != null)
						bitmapArray.add(bitmap);
				} catch (Exception e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
			}
			return bitmapArray;

		}
		/**
		 * After loading pictures into bitmapArray
		 * assign bitmap to imageview with click listeners
		 */
		protected void onPostExecute(ArrayList<Bitmap> result) {
			for (int i = 0; i < artCount; i++) {
				i++;
				String temp = "exhibitArtifact" + i;
				int resID = getResources().getIdentifier(temp, "id",
						"edu.uwp.kcwm");
				imgV = (ImageView) findViewById(resID);
				i--;
				imgV.setImageBitmap(result.get(i));
				imgV.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						for (int i = 1; i <= artCount; i++) {
							ImageView clicked = (ImageView) v;
							int resID = getResources()
									.getIdentifier("exhibitArtifact" + i, "id",
											"edu.uwp.kcwm");
							ImageView found = (ImageView) findViewById(resID);
							// if clicked imageview equals that imageview
							if (clicked == found) {
								// get bitmap from imageview
								clicked.buildDrawingCache(true);
								BitmapDrawable drawable = (BitmapDrawable) clicked
										.getDrawable();
								Bitmap bmap = drawable.getBitmap();
								// save bitmap as jpeg
								String fileName = "artifact";
								try {
									ByteArrayOutputStream bytes = new ByteArrayOutputStream();
									bmap.compress(Bitmap.CompressFormat.JPEG,
											100, bytes);
									FileOutputStream fo = openFileOutput(
											fileName, Context.MODE_PRIVATE);
									fo.write(bytes.toByteArray());
									// close file output
									fo.close();
								} catch (Exception e) {
									e.printStackTrace();
									fileName = null;
								}
								showArtifact(v, i);
							}
						}
					}
				});
			}
			pDialog.dismiss();
		}
	}
}
